<?php
namespace WebSocket\Application;

class UpdateApplication extends Application
{
    private $clients = array();
	private $players = array();

    public function onConnect($client)
    {
    	//$game = new Game();
		
    	$i = count($this->clients);
        $this->clients[$i] = $client;
		$key = array_search($client, $this->clients);
		
		$response = array("action" => "GetPlayerId", "data" => array());
		$response['data']['id'] = $key;
		
		$client->send(json_encode($response));
		
		//Send new player id & position to others clients
		$response = array("action" => "NewPlayerConnected", "data" => array());
		$response['data']['id'] = $key;
		
		foreach ($this->clients as $sendto)
		{
			if($sendto != $client)
				$sendto->send(json_encode($response));
        }
    }

    public function onDisconnect($client)
    {
        $key = array_search($client, $this->clients);
        if ($key) {
            unset($this->clients[$key]);
			unset($this->players[$key]);
        }
		
		
    }

	public function onTick()
    {
    	/*
        if (time() > $this->lastTime + 3) {
            $this->lastTime = time();
            foreach ($this->clients as $sendto) {
                $sendto->send(time());
            }
        }
		/* */
    }

    public function onData($data, $client)
    {
    	/*
    	foreach ($this->clients as $sendto) {
            $sendto->send($data);
        }
		/* */
		
		foreach ($this->clients as $sendto)
		{
			if($sendto != $client)
            	$sendto->send($data);
        }
		return;
		
		if($data['action'] == "UpdatePlayerPosition")
		{
			foreach ($this->clients as $sendto)
			{
				//if($sendto != $client)
	            	$sendto->send(json_encode($data));
	        }
		}
    }
}